package com.sinaapp.gavinzhang.GSpider.http;

import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Gavin on 2015-11-22.
 */
class DispatchServlet extends HttpServlet {
    private static final Logger LOGGER = Logger.getLogger(DispatchServlet.class);

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletMapping servletMapping = getServlet(req);
        if (servletMapping != null) {
            HttpServlet httpServlet = servletMapping.getServlet();
            if (handle(req,resp,httpServlet)) {
                return;
            }
        }
        doGet(req,resp);

    }

    private ServletMapping getServlet(HttpServletRequest req)
    {
        String request = req.getRequestURI().toLowerCase();
        if (request.endsWith("/"))
        {
            request = request.substring(0,request.length()-1);
        }
        return new ServletMapping(request);
    }

    private boolean handle(HttpServletRequest request,HttpServletResponse response,HttpServlet httpServlet)
    {
        if (httpServlet == null) {
            return false;
        }
        return new ServletHandler().handle(request,response,httpServlet);
    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //String query = req.getParameter("query");
        String request = req.getRequestURI();

        String result = "error";
        LOGGER.info(String.format("response is: %s", result));
        resp.setContentType("text/json;charset=utf-8");
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.getWriter().println(result);
    }
}